﻿Imports TNCDAL
Imports HTLibrary

Public Class ucContainers
    Private ctrlCont As New CContainerController
    Private ctrlLineCont As New CLineContController
    Private _idFile As Integer = -1
    Private curFile As tblFile = Nothing
    Private idLine As Integer = -1
    Private currCont As tblCont
    Private curLineCont As tblLineCont = Nothing
    Private isKiemTra As Boolean = False
    Dim uti As New Utilities
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        DataGridViewHelper.DataGridView_InitEvent(dgContainers)
    End Sub

    Public Sub New(ByVal id As Integer)

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        _idFile = id
        Dim fCtrl As New FileRepository
        curFile = fCtrl.SelectRecordById(_idFile)
        Try
            idLine = curFile.tblFileMBLs(0).tblMBL.tblVoyage.ID_Line
        Catch ex As Exception
        End Try
        DataGridViewHelper.DataGridView_InitEvent(dgContainers)
    End Sub

    Private Sub ucContainers_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'xoá trắng textbox
        RefreshForm()
        'kiểm tra xem có nhập đủ thông tin hay chưa
        If idLine < 1 Or _idFile < 1 Then
            MessageBox.Show("Chưa đủ thông tin File để nhập thông tin Containers!")

            btAdd.Enabled = False
            btCopyCont.Enabled = False
            btCancel.Enabled = False
            btDelete.Enabled = False
            btEdit.Enabled = False
            btnRefresh.Enabled = False
            btUpdate.Enabled = False
            btUpdateNew.Enabled = False
            EnableControls(False)
            Exit Sub
        End If

        '------------------hiển thị combox box
        'combo box ContType
        CViewer.BindContTypeToComboBox(cboContType)
        'combo box HBL
        CViewer.BindHBLsToComboBox(cboHBL, _idFile)

        'combo UNit
        CViewer.BindUnitToComboBox(cboUnit)

        'combo Good
        CViewer.BindGoodToComboBox(cboGood)

        BindAutoCompleteToContNo()

        '-----------hiển thị danh sách các container của file
        InitGridView()
        BindContainerGrid()
        
    End Sub

#Region "Buttons"
    Private Sub btnCalculateSUM_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim UnitGW As Double = 0
        Dim UnitNW As Double = 0
        Dim Package As Double = 0
        'If (txtUnitGW.Text <> "") Then
        '    UnitGW = Double.Parse(txtUnitGW.Text)
        'End If
        'If (txtUnitNW.Text <> "") Then
        '    UnitNW = Double.Parse(txtUnitNW.Text)
        'End If
        If (txtPackage.Text <> "") Then
            Package = Double.Parse(txtPackage.Text)
        End If
        Dim GW As Double = UnitGW * Package
        Dim NW As Double = UnitNW * Package
        txtGrossWeight.Text = GW.ToString("#,##0.##")
        txtNetWeight.Text = NW.ToString("#,##0.##")
    End Sub
    Private Sub btAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btAdd.Click
        EnableButtons(True)
        RefreshForm()
        'Init obj
        currCont = New tblCont
        curLineCont = Nothing
        txtContNo.Focus()
    End Sub
    Private Sub btUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btUpdate.Click
        UpdateCont()
    End Sub
    Private Sub btEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btEdit.Click
        EnableButtons(True)
        cboHBL.Focus()
    End Sub

    Private Sub btCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btCancel.Click
        EnableButtons(False)
        'Load info
        Try

            Dim id As Integer = dgContainers.CurrentRow.Cells("ID_Cont").Value
            currCont = ctrlCont.SelectRecordByID(id)
            'Fill company's fields
            FillContForm()

        Catch ex As Exception

        End Try
    End Sub

    Private Sub btDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btDelete.Click
        Dim msg As String = ""
        If (currCont IsNot Nothing) Then
            If (currCont.ContNo <> "") Then
                msg = "Bạn có chắc muốn xoá container " + currCont.ContNo + " ?"
            Else
                msg = "Bạn có chắc muốn xoá container loại " + currCont.tblContType.ContTypeName + " này?"
            End If
            If (MessageBox.Show(msg, "Xác nhận", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
                ctrlCont.DeleteRecord(currCont.ID_Cont)
                BindContainerGrid()
                If (dgContainers.Rows.Count = 0) Then
                    RefreshForm()
                End If
            End If
        End If
    End Sub
    Private Sub btUpdateNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btUpdateNew.Click
        If (UpdateCont() = True) Then
            EnableButtons(True)
            txtContNo.Text = ""
            txtSeal.Text = ""
            cboContType.SelectedIndex = -1
            'Init obj
            currCont = New tblCont
            curLineCont = Nothing
            txtContNo.Focus()
        End If
    End Sub
#End Region

#Region "DataGridView"
    Private Sub dgContainers_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgContainers.SelectionChanged
        'Load info
        Try
            Dim id As Integer = dgContainers.CurrentRow.Cells("ID_Cont").Value
            currCont = ctrlCont.SelectRecordByID(id)

            'Kiểm tra nếu đang cập nhật/thêm mới thì không hiển thị dữ liệu
            If btUpdate.Enabled = True Then
                Exit Sub
            End If

            'Fill company's fields
            FillContForm()

        Catch ex As Exception

        End Try

    End Sub
#End Region

#Region "Utilities"
    Private Function CheckSeal() As Boolean
        'kiểm tra xem có tồn tại trong file chưa
        If (txtSeal.Text <> "" And ctrlCont.CheckExistsSealInFile(txtSeal.Text, currCont.ID_Cont, _idFile) = True) Then
            MessageBox.Show("Seal này đã có trong danh sách!")
            'txtSeal.Text = ""
            'Return False
        End If
        Return True
    End Function
    Private Function CheckContainer() As Boolean
        If (txtContNo.TextLength <> 11) Then
            MessageBox.Show("Cont No phải đủ 11 ký tự!")
            curLineCont = Nothing
            Return False
        End If
        curLineCont = ctrlLineCont.SelectRecordByContNoAndLine(idLine, txtContNo.Text)
        'kiểm tra xem cái ContNo này đã tồn tại chưa
        If (curLineCont Is Nothing) Then
            If (MessageBox.Show("Cont No này chưa có. Bạn muốn thêm không?", "Thông báo", MessageBoxButtons.YesNo) = vbYes) Then
                'thêm vào
                curLineCont = New tblLineCont
                curLineCont.ID_LineCont = -1
                curLineCont.IsActive = True
                curLineCont.ContNo = txtContNo.Text
                curLineCont.ID_ContType = cboContType.SelectedValue
                curLineCont.ID_Line = idLine
                'enable Cont Type lên
                cboContType.Enabled = True
                'cboContType.Focus()
            Else
                txtContNo.Text = ""
                Return False
            End If
        Else 'đã có rồi
            'kiểm tra xem có tồn tại trong file chưa
            If (ctrlCont.CheckExistsContNoInFile(txtContNo.Text, currCont.ID_Cont, _idFile) = True) Then
                MessageBox.Show("Container này đã có trong danh sách!")
                'txtContNo.Text = ""
                'curLineCont = Nothing
                'Return False
            End If
            curLineCont = ctrlLineCont.SelectRecordByContNoAndLine(idLine, txtContNo.Text)
            If (curLineCont.ID_ContType.HasValue) Then
                cboContType.SelectedValue = curLineCont.ID_ContType
                cboContType.Enabled = False
            Else
                cboContType.Enabled = True
            End If
        End If
        Return True
    End Function

    Private Sub BindAutoCompleteToContNo()
        'tạo chức năng auto complete cho Cont No
        Dim source = New AutoCompleteStringCollection()

        Dim ContNoList = ctrlLineCont.SelectContNoByLine(idLine)
        source.AddRange(ContNoList)

        'Textbox MBLNo
        txtContNo.AutoCompleteSource = AutoCompleteSource.CustomSource
        txtContNo.AutoCompleteCustomSource = source
        txtContNo.AutoCompleteMode = AutoCompleteMode.SuggestAppend
    End Sub
    Public Sub DisableControlWhenBooking()
        cboHBL.Enabled = False
    End Sub
    Public Sub InitGridView()
        dgContainers.AllowUserToAddRows = False
        dgContainers.AllowUserToDeleteRows = False
        dgContainers.ReadOnly = True
    End Sub
    Private Sub BindContainerGrid()
        'đọc danh sách các container của file theo idFile
        Dim q As IQueryable = ctrlCont.SelectContsByFile(_idFile)
        dgContainers.DataSource = q
        EnableButtons(False)
    End Sub
    Private Sub EnableButtons(ByVal val As Boolean)
        btUpdate.Enabled = val
        btCancel.Enabled = val
        btUpdateNew.Enabled = val

        btAdd.Enabled = Not val
        btEdit.Enabled = Not val
        btDelete.Enabled = Not val
        btCopyCont.Enabled = Not val

        EnableControls(val)
        'nếu là cont lẻ thì chỉ cho nhập 1 và chỉ 1 cont thôi
        If (curFile.IsFCL = False) Then
            btUpdateNew.Enabled = False
            If (dgContainers.Rows.Count = 1) Then
                btAdd.Enabled = False
                btCopyCont.Enabled = False
            End If
        End If
        'nếu ko có cont nào thì disable nút copy
        If (dgContainers.Rows.Count < 1) Then
            btCopyCont.Enabled = False
            btEdit.Enabled = False
            btDelete.Enabled = False
        End If
    End Sub
    Private Sub EnableControls(ByVal val As Boolean)
        txtCBM.ReadOnly = Not val
        txtContNo.ReadOnly = Not val
        txtNote.ReadOnly = Not val
        txtPackage.ReadOnly = Not val
        txtSeal.ReadOnly = Not val
        txtNetWeight.ReadOnly = Not val
        txtGrossWeight.ReadOnly = Not val

        cboHBL.Enabled = val
        cboGood.Enabled = val
        cboUnit.Enabled = val
        cboContType.Enabled = val

        dgContainers.Enabled = Not val
    End Sub
    Private Sub RefreshForm()
        cboGood.SelectedIndex = -1
        cboHBL.SelectedIndex = -1
        cboUnit.SelectedIndex = -1
        txtCBM.Text = ""
        txtContNo.Text = ""
        txtNote.Text = ""
        txtPackage.Text = ""
        txtNetWeight.Text = ""
        txtSeal.Text = ""
        txtGrossWeight.Text = ""
        cboContType.SelectedIndex = -1
    End Sub

    Private Function UpdateCont() As Boolean
        'kiểm tra tại đây
        If (cboContType.SelectedIndex < 0) Then
            MessageBox.Show("Chưa chọn cont type!")
            cboContType.Focus()
            Return False
        End If
        If (CheckSeal() = False) Then
            Return False
        End If
        'thêm line cont
        Dim idCurr As Integer = currCont.ID_Cont
        With currCont
            .ID_File = _idFile
            .Description = txtNote.Text
            .Seal = txtSeal.Text
            .ContNo = txtContNo.Text
            .ID_ContType = cboContType.SelectedValue
            'cập nhật lại line cont
            If (curLineCont Is Nothing) Then
                curLineCont = ctrlLineCont.SelectRecordByContNoAndLine(idLine, txtContNo.Text)
                If (curLineCont IsNot Nothing) Then
                    If (curLineCont.ID_ContType <> cboContType.SelectedValue) Then
                        curLineCont.ID_ContType = cboContType.SelectedValue
                        ctrlLineCont.UpdateRecordWithoutAttach(curLineCont)
                    End If
                End If
            Else
                If (curLineCont.ID_LineCont = -1) Then
                    ctrlLineCont.InsertRecord(curLineCont)
                    BindAutoCompleteToContNo()
                Else
                    If (curLineCont.ID_ContType <> cboContType.SelectedValue) Then
                        curLineCont.ID_ContType = cboContType.SelectedValue
                        ctrlLineCont.UpdateRecordWithoutAttach(curLineCont)
                    End If
                End If
            End If

            If (txtCBM.Text <> "") Then
                .CBM = CDbl(txtCBM.Text)
            Else
                .CBM = 0
            End If
            If (txtPackage.Text <> "") Then
                .Package = CInt(txtPackage.Text)
            Else
                .Package = 0
            End If
            If (cboUnit.Text <> "") Then
                .ID_Unit = cboUnit.SelectedValue
            Else
                .ID_Unit = Nothing
            End If

            If (txtNetWeight.Text <> "") Then
                .NW = CDbl(txtNetWeight.Text)
            Else
                .NW = 0
            End If
            If (txtGrossWeight.Text <> "") Then
                .GW = CDbl(txtGrossWeight.Text)
            Else
                .GW = 0
            End If

            If (cboHBL.Text <> "") Then
                .ID_HBL = cboHBL.SelectedValue
            Else
                .ID_HBL = Nothing
            End If
            If (cboGood.Text <> "") Then
                .ID_Good = cboGood.SelectedValue
            Else
                .ID_Good = Nothing
            End If
        End With
        'Dim idCurr As Integer = currPort.ID_Port
        If currCont.ID_Cont > 0 Then
            ctrlCont.UpdateRecordWithoutAttach(currCont)
        Else
            ctrlCont.InsertRecord(currCont)
            idCurr = currCont.ID_Cont
        End If
        'Refresh gridview
        BindContainerGrid()
        Dim indexRow As Integer = -1
        'lấy ra vị trí của port vừa thêm hoặc chỉnh sửa vào
        indexRow = FindIndexOfContInGrid(idCurr)
        If (indexRow > -1) Then
            'Set current row
            dgContainers.CurrentCell = dgContainers.Rows(indexRow).Cells(1)
            dgContainers.Rows(indexRow).Selected = True
        End If

        'Refresh buttons
        EnableButtons(False)
        Return True
    End Function
    Public Sub CopyContForm()
        If (currCont IsNot Nothing) Then
            txtNote.Text = currCont.Description
            txtSeal.Text = ""
            txtContNo.Text = ""
            If (currCont.ID_ContType.HasValue) Then
                cboContType.SelectedValue = currCont.ID_ContType
            Else
                cboContType.Text = ""
                cboContType.SelectedIndex = -1
            End If

            If (currCont.CBM.HasValue) Then
                txtCBM.Text = currCont.CBM.Value.ToString("#,##0.0000")
            Else
                txtCBM.Text = ""
            End If

            If (currCont.Package.HasValue) Then
                txtPackage.Text = currCont.Package.Value.ToString("#,##0")
            Else
                txtPackage.Text = ""
            End If

            If (currCont.NW.HasValue) Then
                txtNetWeight.Text = currCont.NW.Value.ToString("#,##0.000")
            Else
                txtNetWeight.Text = ""
            End If

            If (currCont.GW.HasValue) Then
                txtGrossWeight.Text = currCont.GW.Value.ToString("#,##0.000")
            Else
                txtGrossWeight.Text = ""
            End If

            If (currCont.ID_HBL.HasValue) Then
                cboHBL.SelectedValue = currCont.ID_HBL
            Else
                cboHBL.Text = ""
                cboHBL.SelectedIndex = -1
            End If

            If (currCont.ID_Good.HasValue) Then
                cboGood.SelectedValue = currCont.ID_Good
            Else
                cboGood.Text = ""
                cboGood.SelectedIndex = -1
            End If
            If (currCont.ID_Unit.HasValue) Then
                cboUnit.SelectedValue = currCont.ID_Unit
            Else
                cboUnit.Text = ""
                cboUnit.SelectedIndex = -1
            End If
        Else
            RefreshForm()
        End If
    End Sub
    Public Sub FillContForm()
        If (currCont IsNot Nothing) Then
            txtNote.Text = currCont.Description
            txtSeal.Text = currCont.Seal
            txtContNo.Text = currCont.ContNo
            If (currCont.ID_ContType.HasValue) Then
                cboContType.SelectedValue = currCont.ID_ContType
            Else
                cboContType.Text = ""
                cboContType.SelectedIndex = -1
            End If

            'txtCBM.Text = IIf(currCont.CBM.HasValue, currCont.CBM.Value.ToString("#,##0.0000"), "")
            'txtPackage.Text = IIf(currCont.Package.HasValue, currCont.Package.Value.ToString("#,##0"), "")
            'txtNetWeight.Text = IIf(currCont.NW.HasValue, currCont.NW.Value.ToString("#,##0.000"), "")
            'txtGrossWeight.Text = IIf(currCont.GW.HasValue, currCont.GW.Value.ToString("#,##0.000"), "")
            If (currCont.CBM.HasValue) Then
                txtCBM.Text = currCont.CBM.Value.ToString("#,##0.0000")
            Else
                txtCBM.Text = ""
            End If

            If (currCont.Package.HasValue) Then
                txtPackage.Text = currCont.Package.Value.ToString("#,##0")
            Else
                txtPackage.Text = ""
            End If

            If (currCont.NW.HasValue) Then
                txtNetWeight.Text = currCont.NW.Value.ToString("#,##0.000")
            Else
                txtNetWeight.Text = ""
            End If

            If (currCont.GW.HasValue) Then
                txtGrossWeight.Text = currCont.GW.Value.ToString("#,##0.000")
            Else
                txtGrossWeight.Text = ""
            End If

            If (currCont.ID_HBL.HasValue) Then
                cboHBL.SelectedValue = currCont.ID_HBL
            Else
                cboHBL.Text = ""
                cboHBL.SelectedIndex = -1
            End If

            If (currCont.ID_Good.HasValue) Then
                cboGood.SelectedValue = currCont.ID_Good
            Else
                cboGood.Text = ""
                cboGood.SelectedIndex = -1
            End If
            If (currCont.ID_Unit.HasValue) Then
                cboUnit.SelectedValue = currCont.ID_Unit
            Else
                cboUnit.Text = ""
                cboUnit.SelectedIndex = -1
            End If
        End If
    End Sub

    Private Function FindIndexOfContInGrid(ByVal id As Integer) As Integer
        Dim index As Integer = -1
        For Each row As DataGridViewRow In dgContainers.Rows
            If (row.Cells("ID_Cont").Value = id) Then
                index = row.Index
                Exit For
            End If
        Next
        Return index
    End Function
#End Region

#Region "Controls Events"
    Private Sub KiemTraNumbericTextBox(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCBM.KeyUp, txtPackage.KeyUp, txtNetWeight.KeyUp, txtGrossWeight.KeyUp
        Dim txt As TextBox = sender
        If (IsNumeric(txt.Text) = False And txt.Text <> "") Then
            MessageBox.Show("Bạn phải nhập số!")
            txt.Text = ""
            txt.Focus()
        End If
    End Sub
    Private Sub cboContType_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboContType.Leave
        If (cboContType.Enabled = False Or btUpdate.Enabled = False Or curLineCont Is Nothing) Then
            Exit Sub
        End If
        If (cboContType.Text <> "") Then
            If curLineCont IsNot Nothing Then
                curLineCont.ID_ContType = cboContType.SelectedValue
            End If
            'Else
            '    MessageBox.Show("Chưa chọn thông tin loại container!")
            '    cboContType.Focus()
            '    Exit Sub
        End If
    End Sub

    Private Sub txtContNo_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtContNo.Validating
        'nếu đang ở chế độ xem thì không kiểm tra
        If (btUpdate.Enabled = False) Then
            e.Cancel = False
            Exit Sub
        End If
        'nếu không nhập cont no thì không kiểm tra
        If (txtContNo.Text = "") Then
            e.Cancel = False
            Exit Sub
        End If
        'THỰC HIỆN KIỂM TRA
        If (CheckContainer() = False) Then
            e.Cancel = True
        End If
    End Sub

    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        '------------------hiển thị combox box
        'combo box ContType
        CViewer.BindContTypeToComboBox(cboContType)
        'combo box HBL
        CViewer.BindHBLsToComboBox(cboHBL, _idFile)

        'combo UNit
        CViewer.BindUnitToComboBox(cboUnit)

        'combo Good
        CViewer.BindGoodToComboBox(cboGood)

        BindAutoCompleteToContNo()

        'hiển thị lại thông tin cur cont
        FillContForm()
    End Sub
#End Region

    Private Sub btCopyCont_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btCopyCont.Click
        EnableButtons(True)
        CopyContForm()
        'Init obj
        currCont = New tblCont
        curLineCont = Nothing
        txtContNo.Focus()
    End Sub

    Private Sub txtSeal_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSeal.Leave
        CheckSeal()
    End Sub
    Private Sub txtNum_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtGrossWeight.Leave, txtNetWeight.Leave
        Dim txt As TextBox = sender
        Try
            Dim so As Double = CDbl(txt.Text)
            txt.Text = so.ToString("#,##0.000")
        Catch ex As Exception
        End Try
    End Sub

    'Private Sub txtCBM_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPackage.TextChanged, txtNetWeight.TextChanged, txtGrossWeight.TextChanged, txtCBM.TextChanged
    '    Dim txt As TextBox = sender
    '    Dim uti As New Utilities
    '    uti.FormatCurr(txt)
    'End Sub

    Private Sub panelButtons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles panelButtons.Click

    End Sub

    Private Sub txtCBM_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCBM.Leave
        Dim txt As TextBox = sender
        Try
            Dim so As Double = CDbl(txt.Text)
            txt.Text = so.ToString("#,##0.0000")
        Catch ex As Exception
        End Try
    End Sub

    Private Sub txtPackage_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPackage.Leave
        Dim txt As TextBox = sender
        Try
            Dim so As Integer = CInt(txt.Text)
            txt.Text = so.ToString("#,##0")
        Catch ex As Exception
        End Try
    End Sub
End Class
